#shaiya SMOD parser

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class ShaiyaSMOD(Model3D):

    def __init__(self, obj3D=None, inFile=None, outFile=None):
        '''Initialize am MQO Object.'''
        
        super(ShaiyaSMOD, self).__init__("ShaiyaSMOD")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
    
    def parse_file(self, filename):

        #skip header
        self.inFile.seek(0x28)
        
        meshNum = self.inFile.read_long()
        for i in range(0, meshNum):
            
            #null-terminated name
            charCount = self.inFile.read_long()
            texName = self.inFile.read_string(charCount).strip("\x00")
            matName = texName[:-4]
            print texName
            objName = "%s[%d]" %(filename, i)
            
            
            self.create_object(objName)
            self.create_material(i)
            self.add_material_name(i, matName)
            self.add_texture_name(i, texName)
            
            vertCount = self.inFile.read_long()
            
            for j in range(0, vertCount):
                
                vx, vy, vz = self.inFile.read_float(3)
                self.inFile.read(16)
                tu, tv = self.inFile.read_float(2)
                
                vx = float(vx) * -1
                self.create_vertex(objName, j)
                self.add_coords(objName, j, [vx, vy, vz])
                self.add_vert_uv(objName, j, [tu, tv])
            
            faceNum = self.inFile.read_long()
            
            for j in range(0, faceNum):
                v1, v2, v3 = self.inFile.read_short(3)
                
                self.create_face(objName, j)
                self.add_face_verts(objName, j, [v1,v2,v3])
                self.add_face_material(objName, j, i)
        
def read_file(path):
    
    filename, ext = os.path.splitext(os.path.basename(path))
    openFile = StructReader(open(path, 'rb'))
    obj = ShaiyaSMOD("ShaiyaSMOD", inFile=openFile)
    obj.parse_file(filename)
    openFile.close()
    return obj

def definitions():
    
    return "", "SMOD", "Shaiya SMOD"
        
if __name__ == '__main__':
        
    file1 = "door.SMOD"
    file2 = "A2_DwarfCoal_01.SMOD"
    file3 = 'stone_boundary1f.smod'
    file4 = 'GuardTower_Ladder_New.SMOD'
    file5 = 'login_A.SMOD'
    file6 = 'Login_stonedapple.SMOD'
    obj = read_file(file2)